package com.pucong.gitee.database.backup.business.database.util;

import com.pucong.gitee.database.backup.common.entity.database.AutoDataSource;
import com.pucong.gitee.database.backup.common.selfenum.DatabaseDriverClassEnum;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.business.database.mapper.AutoExeSqlLogMapper;
import org.apache.commons.lang3.StringUtils;

public class OperationServiceMssqlImpl extends AbstractOperationService {

    private static final String URL_PREFIX = "jdbc:sqlserver://";

    private static final String URL_LAST = "useUnicode=true&characterEncoding=UTF-8&allowMultiQueries=true";

    public OperationServiceMssqlImpl(AutoDataSource autoDataSource, AutoExeSqlLogMapper autoExeSqlLogMapper) {
        super(autoDataSource, autoExeSqlLogMapper);
    }

    @Override
    public void initUrl() {
        this.url = URL_PREFIX + autoDataSource.getHost() + ":" + autoDataSource.getPort() + ";database=" + autoDataSource.getDatabaseName();
        this.driverClassName = DatabaseDriverClassEnum.sqlserver.getClassName();
    }

    @Override
    public String generatePageSql(String sql, Integer pageNum, Integer pageSize) {
        if(StringUtils.isBlank(sql)){
            throw new BusinessException("sql语句为空");
        }
        if(pageNum == null){
            pageNum = 1;
        }
        if(pageSize == null){
            pageSize = 10;
        }

        sql = "SELECT TOP " + (pageSize * pageNum)
                + " ROW_NUMBER() OVER ( ORDER BY (SELECT null) )  AS rownum , t.* from ( " + sql+ " ) t ";
        sql = " SELECT * FROM ( " + sql + " ) AS temp WHERE temp.rownum > " +  (pageSize * (pageNum- 1));
        return sql;
    }
}
